package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.repository.CountRepository;
import com.hualude.roadsign.repository.SignalMachineFaultCountRepository;
import com.hualude.roadsign.service.MachineLocationCountService;
import com.hualude.roadsign.utils.ExportExcelUtil;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.List;

/**
 * Created by pjn on 2017/9/20.
 */
@Service
public class MachineLocationCountServiceImpl implements MachineLocationCountService {
    @Resource
    private SignalMachineFaultCountRepository signalMachineFaultCountRepository;
    @Resource
    private CountRepository countRepository;

    public DTResponseDto getMachine4DT(Integer userId, Integer orgId, DTRequestDto dtRequestDto) throws Exception {
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        Integer count = signalMachineFaultCountRepository.getMachineCount4DT(dtRequestDto, authorityDto.getActor(), authorityDto.getOrgIds());
        List<SignalMachineDto> dto4DTs = signalMachineFaultCountRepository.getMachine4DT(dtRequestDto, authorityDto.getActor(), authorityDto.getOrgIds());
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    public List<String> getProvinceName(Integer userId, Integer orgId) throws Exception {
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        return signalMachineFaultCountRepository.getProvinceName(authorityDto.getOrgIds());
    }

    public List<String> getCityName(Integer userId, Integer orgId, String provinceName) throws Exception {
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        return signalMachineFaultCountRepository.getCityName(authorityDto.getOrgIds(), provinceName);
    }

    public List<String> getAllAreaName(Integer userId, Integer orgId, String provinceName, String cityName) throws Exception {
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        return signalMachineFaultCountRepository.getAllAreaName(authorityDto.getOrgIds(), provinceName, cityName);
    }


    public List<String> getStartRoadName(Integer userId, Integer orgId, String provinceName, String cityName, String areaName,
                                         String endRoadName) throws Exception {
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        List<String> roadStartName = signalMachineFaultCountRepository.getStartRoadName(authorityDto.getOrgIds(), provinceName, cityName,
                areaName, endRoadName);
        return roadStartName;
    }

    public List<String> getEndRoadName(Integer userId, Integer orgId, String startRoad, String provinceName, String cityName,
                                       String areaName) throws Exception {
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        return signalMachineFaultCountRepository.getEndRoadName(authorityDto.getOrgIds(), startRoad, provinceName, cityName, areaName);
    }

    public List<Integer> getSignalMachineTypeCounts(Integer userId, Integer orgId, String time, String province, String city, String area) throws Exception {
        if (province.equals("-1")) province = "";
        if (city.equals("-1")) city = "";
        if (area.equals("-1")) area = "";
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        String orgIds = orgId.toString();
        if (orgId == -1) {
            if (authorityDto.getActor() == 7 || authorityDto.getActor() == 1) {
                orgIds = authorityDto.getOrgIds();
            }
        }
        return signalMachineFaultCountRepository.getSignalMachineTypeCounts(orgIds, time, province, city, area);
    }


    //得到用户公司及其子公司IDs，用户最终角色
    public AuthorityDto getActorAndOrgIds(AuthorityDto authorityDto) {
        try {
            String actorIds = countRepository.getactorIds(authorityDto.getUserId());
            String orgIds = authorityDto.getOrgId().toString();
            if (orgIds.equals("-1")) {
                orgIds = countRepository.getRealOrgIds(authorityDto.getUserId()).toString();
            }
            Integer actor = Integer.parseInt(actorIds.split(",")[0]);//用户最终角色 1系统>7主管>其它
            Integer isManager = actorIds.indexOf("1");//系统管理员
            Integer isChief = actorIds.indexOf("7");//主管管理员
            if (isManager >= 0) {
                actor = 1;
                String ChildOrgIds = countRepository.getOrgIds();
                if (!ChildOrgIds.equals("")) {
                    orgIds = ChildOrgIds;
                }
            } else if (isChief >= 0) {
                actor = 7;
                String ChildOrgIds = countRepository.getChildOrgIds(Integer.parseInt(orgIds));
                if (!ChildOrgIds.equals("")) {
                    orgIds += "," + ChildOrgIds;
                }
            }
            authorityDto.setActor(actor);
            authorityDto.setOrgIds(orgIds);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return authorityDto;
    }

    public HSSFWorkbook downMachineByExcel(String search, Integer userId, Integer orgId) throws Exception {
        DTRequestDto dtRequestDto = new DTRequestDto(0, 0, 0, search);
        AuthorityDto authorityDto = new AuthorityDto(userId, orgId);
        authorityDto = getActorAndOrgIds(authorityDto);
        List<SignalMachineDto> dto4DTs = signalMachineFaultCountRepository.getMachineDtos4DT(dtRequestDto, authorityDto.getActor(), authorityDto.getOrgIds(), authorityDto.getUserId());
        List<BigInteger> counts = signalMachineFaultCountRepository.getMachineCounts(dtRequestDto, authorityDto.getActor(), authorityDto.getOrgIds(), authorityDto.getUserId());
        for (int i = 0; i < dto4DTs.size(); i++) {
            dto4DTs.get(i).setMachineCount(counts.get(i).intValue());
        }
        for (SignalMachineDto signalMachineDto : dto4DTs) {
            Integer[] type = {0, 0, 0};
            List<Integer> roadSignType = signalMachineFaultCountRepository.getPerMachineCountsByRoad(signalMachineDto.getSignalMachineProvince(),
                    signalMachineDto.getSignalMachineCity(), signalMachineDto.getSignalMachineArea(), signalMachineDto.getSignalMachineOrgName());
            for (int i = 0; i < roadSignType.size(); i++)
                type[roadSignType.get(i)]++;
            signalMachineDto.setMachineType(type);
        }
        //表头String数组
        String[] excelHeader = new String[]{"序号", "维护公司", "省份", "市", "区域", "信号机总数", "A类信号机", "B类信号机", "C类信号机"};
        //创建工具类对象
        ExportExcelUtil excelUtil = new ExportExcelUtil();
        //创建样式
        HSSFCellStyle style = excelUtil.createExStyle("宋体", 10, HSSFFont.BOLDWEIGHT_NORMAL, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER);
        HSSFCellStyle headStyle = excelUtil.createExStyle("宋体", 10, HSSFFont.BOLDWEIGHT_BOLD, HSSFCellStyle.ALIGN_CENTER, HSSFCellStyle.VERTICAL_CENTER);
        //添加边框
        excelUtil.setBorder(style);
        excelUtil.setBorder(headStyle);
        //创建工作表
        HSSFSheet sheet = excelUtil.createExSheet("sheet1", 300, 15);
        //添加表头
        excelUtil.createExSheetHeader(sheet, headStyle, 0, excelHeader);
        //添加内容
        for (int i = 0; i < dto4DTs.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            excelUtil.addExInfo(row, 0, style, i + 1);
            excelUtil.addExInfo(row, 1, style, dto4DTs.get(i).getSignalMachineOrgName());
            excelUtil.addExInfo(row, 2, style, dto4DTs.get(i).getSignalMachineProvince());
            excelUtil.addExInfo(row, 3, style, dto4DTs.get(i).getSignalMachineCity());
            excelUtil.addExInfo(row, 4, style, dto4DTs.get(i).getSignalMachineArea());
            excelUtil.addExInfo(row, 5, style, dto4DTs.get(i).getMachineCount());
            excelUtil.addExInfo(row, 6, style, dto4DTs.get(i).getMachineType()[0]);
            excelUtil.addExInfo(row, 7, style, dto4DTs.get(i).getMachineType()[1]);
            excelUtil.addExInfo(row, 8, style, dto4DTs.get(i).getMachineType()[2]);
        }
        return excelUtil.getHssfWorkbook();
    }

}
